package site.lanmushan.framework.mapper.wrapper;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.schema.Column;
import site.lanmushan.framework.mapper.params.WhereQueryParam;
import site.lanmushan.framework.util.utils.StringCommonUtil;

import javax.persistence.Table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
public abstract class AbstractFormatQueryWrapper implements FormatWrapper {
    protected List<WhereQueryParam> whereQueryParams = new ArrayList<>(0);
    protected Expression expression;
    protected List<String> columns=new ArrayList<>();
    protected Map<String, Object> params = new HashMap<>();
    protected String tableName;
    protected String alias = "tb";

    public AbstractFormatQueryWrapper() {
    }

    public AbstractFormatQueryWrapper(String tableName) {
        this.tableName = tableName;
    }

    public AbstractFormatQueryWrapper(String tableName, String alias) {
        this.tableName = tableName;
        this.tableName = alias;
    }

    public AbstractFormatQueryWrapper(Class tClass) {
        this.tableName = createTableName(tClass);
    }

    public AbstractFormatQueryWrapper(Class tClass, String alias) {
        this.tableName = createTableName(tClass);
        this.tableName = alias;
    }

    protected Column createColumn(String column) {
        if (column.startsWith(alias)) {
            return new Column(column);
        } else {
            return new Column( "{{alias}}." + column);
        }
    }

    protected String createTableName(Class tClass) {
        Table table = (Table) tClass.getAnnotation(Table.class);
        if (table != null) {
            return table.name();
        }
        return StringCommonUtil.camelToUnderline(tClass.getName(), '_');

    }

    @Override
    public String getAlias() {
        return alias;
    }

    @Override
    public String getTableName() {
        return tableName;
    }

    @Override
    public String getWhereString() {
        if(expression!=null)
        {
            return expression.toString();
        }
        return null;
    }

    @Override
    public List<String> getColumns() {
        return columns.size()==0?null:columns;
    }
}
